import Mock from 'mockjs'

// 设置响应延迟
Mock.setup({
  timeout: '200-600'
})

// 通用的响应体格式
const successResponse = (data, message = 'success') => {
  return {
    code: 200,
    message,
    data
  }
}

const errorResponse = (message = 'error', code = 500) => {
  return {
    code,
    message,
    data: null
  }
}

// 生成用户信息的通用函数
const generateUserInfo = (data = {}) => {
  return Mock.mock({
    id: '@id',
    username: '@word(5,10)',
    nickname: '@cname',
    avatar: '@image("100x100")',
    email: '@email',
    gender: '@integer(0,2)',
    birthday: '@date',
    introduction: '@cparagraph(1)',
    location: '@city',
    'followCount|0-999': 100,
    'fansCount|0-999': 100,
    'likedCount|0-9999': 1000,
    'isFollowed|1': false,
    ...data
  })
}

// 生成帖子列表的通用函数
const generatePosts = (params = {}) => {
  const { page = 1, limit = 10 } = params
  return Mock.mock({
    'items|10': [{
      'id|+1': 1,
      title: '@ctitle(5,20)',
      content: '@cparagraph(3,7)',
      'coverImage|1': ['/001.png', '/002.png', '/003.png', '/004.png', '/005.png'],
      'images|1-5': ['/001.png', '/002.png', '/003.png', '/004.png', '/005.png'],
      'tags|1-3': ['@ctitle(2,4)'],
      'viewCount|100-9999': 1000,
      'likeCount|10-999': 100,
      'collectCount|10-999': 100,
      'commentCount|0-99': 50,
      location: '@city',
      createTime: '@datetime',
      'isLiked|1': false,
      'isCollected|1': false,
      author: {
        id: '@id',
        nickname: '@cname',
        avatar: '@image("100x100")',
        'isFollowed|1': false
      }
    }],
    total: 100,
    page,
    limit
  })
}

// 生成通知的辅助函数
const generateNotification = () => {
  return {
    id: Mock.Random.id(),
    type: Mock.Random.pick(['like', 'comment', 'follow', 'system']),
    title: '@ctitle(10,20)',
    content: '@cparagraph(1,2)',
    createTime: '@datetime',
    isRead: '@boolean',
    sender: {
      id: '@id',
      nickname: '@cname',
      avatar: '@image("50x50")'
    },
    targetId: '@id',
    targetType: Mock.Random.pick(['post', 'comment', 'user']),
    targetContent: '@csentence(10,20)'
  }
}

// // ==================== 认证相关接口 ====================
// // 用户登录
// Mock.mock(/\/api\/auth\/login/, 'post', (options) => {
//   const { email, password, remember } = JSON.parse(options.body)
//   if (email && password) {
//     // 模拟检查邮箱和密码
//     if (email === 'test@example.com' && password === '123456') {
//       return successResponse({
//         token: Mock.Random.guid(),
//         userInfo: {
//           id: Mock.Random.id(),
//           email: email,
//           nickname: Mock.Random.cname(),
//           avatar: Mock.Random.image('100x100'),
//           gender: Mock.Random.integer(0, 2),
//           birthday: Mock.Random.date(),
//           introduction: Mock.Random.cparagraph(1),
//           location: Mock.Random.city(),
//           followCount: Mock.Random.integer(0, 999),
//           fansCount: Mock.Random.integer(0, 999),
//           likedCount: Mock.Random.integer(0, 9999),
//           createTime: Mock.Random.datetime(),
//           lastLoginTime: Mock.Random.datetime()
//         }
//       })
//     }
//   }
//   return errorResponse('邮箱或密码错误', 401)
// })

// 用户登出
Mock.mock(/\/api\/auth\/logout/, 'post', () => {
  return successResponse({ success: true })
})

// 获取当前用户信息
// Mock.mock(/\/api\/auth\/me/, 'get', () => {
//   return successResponse(generateUserInfo())
// })

// 验证码相关
Mock.mock(/\/api\/auth\/send-code/, 'post', () => {
  return successResponse({
    message: '验证码已发送',
    expireTime: Date.now() + 300000
  })
})

Mock.mock(/\/api\/auth\/verify-code/, 'post', () => {
  return successResponse({
    valid: true,
    message: '验证码正确'
  })
})

// 重置密码
Mock.mock(/\/api\/auth\/reset-password/, 'post', () => {
  return successResponse({
    success: true,
    message: '密码重置成功'
  })
})

// 刷新token
Mock.mock(/\/api\/auth\/refresh/, 'post', () => {
  return successResponse({
    token: 'mock-refresh-token-' + Date.now()
  })
})

// ==================== 用户相关接口 ====================
// 用户注册
// Mock.mock(/\/api\/auth\/register/, 'post', (options) => {
//   const data = JSON.parse(options.body)
//   return successResponse({
//     message: '注册成功',
//     userInfo: generateUserInfo(data)
//   })
// })

// 更新用户信息
Mock.mock(/\/api\/users\/profile/, 'put', (options) => {
  const data = JSON.parse(options.body)
  return successResponse(generateUserInfo(data))
})

// 更新用户头像
Mock.mock(/\/api\/users\/avatar/, 'put', () => {
  return successResponse({
    avatar: Mock.Random.image('100x100')
  })
})

// 修改密码
Mock.mock(/\/api\/users\/password/, 'put', () => {
  return successResponse({ success: true })
})

// 获取用户信息
Mock.mock(/\/api\/users\/\w+$/, 'get', (options) => {
  const userId = options.url.match(/\/users\/(\w+)/)[1]
  return successResponse(generateUserInfo({ id: userId }))
})

// 关注/取消关注
Mock.mock(/\/api\/users\/\w+\/follow/, 'post', () => {
  return successResponse({ success: true })
})

Mock.mock(/\/api\/users\/\w+\/unfollow/, 'delete', () => {
  return successResponse({ success: true })
})

// 用户统计信息
Mock.mock(/\/api\/users\/\w+\/stats/, 'get', () => {
  const stats = Mock.mock({
    'postsCount|0-100': 50,
    'followingCount|0-500': 100,
    'followersCount|0-1000': 200,
    'likedCount|0-9999': 1000,
    'viewsCount|0-99999': 5000
  })
  return successResponse(stats)
})

// 用户关注列表
Mock.mock(/\/api\/users\/\w+\/followings(\?.+)?$/, 'get', (options) => {
  const params = options.url.includes('?')
    ? Object.fromEntries(new URLSearchParams(options.url.split('?')[1]))
    : {}
  const users = Mock.mock({
    [`items|${params.limit || 10}`]: [generateUserInfo]
  })
  return successResponse({
    ...users,
    total: 128,
    page: parseInt(params.page) || 1,
    limit: parseInt(params.limit) || 20
  })
})

// 用户粉丝列表
Mock.mock(/\/api\/users\/\w+\/followers(\?.+)?$/, 'get', (options) => {
  const params = options.url.includes('?')
    ? Object.fromEntries(new URLSearchParams(options.url.split('?')[1]))
    : {}
  const users = Mock.mock({
    [`items|${params.limit || 10}`]: [generateUserInfo]
  })
  return successResponse({
    ...users,
    total: 256,
    page: parseInt(params.page) || 1,
    limit: parseInt(params.limit) || 20
  })
})

// 用户收藏列表
Mock.mock(/\/api\/users\/\w+\/collections(\?.+)?$/, 'get', (options) => {
  const params = options.url.includes('?')
    ? Object.fromEntries(new URLSearchParams(options.url.split('?')[1]))
    : {}
  return successResponse(generatePosts(params))
})

// 用户笔记本
Mock.mock(/\/api\/users\/\w+\/notebooks/, 'get', () => {
  const notebooks = Mock.mock({
    'items|3-5': [{
      'id|+1': 1,
      name: '@ctitle(2,4)',
      description: '@csentence(5,10)',
      'isPrivate|1': false,
      'count|0-100': 50
    }]
  })
  return successResponse(notebooks.items)
})

// 创建笔记本
Mock.mock(/\/api\/users\/notebooks/, 'post', (options) => {
  const data = JSON.parse(options.body)
  return successResponse({
    ...data,
    id: Mock.Random.id(),
    count: 0,
    createTime: Mock.Random.datetime()
  })
})

// ==================== 帖子相关接口 ====================
// 发现页帖子列表
Mock.mock(/\/api\/posts\/discover(\?.+)?$/, 'get', (options) => {
  const params = options.url.includes('?') 
    ? Object.fromEntries(new URLSearchParams(options.url.split('?')[1]))
    : {}
  return successResponse(generatePosts(params))
})

// 热门帖子列表
Mock.mock(/\/api\/posts\/hot(\?.+)?$/, 'get', (options) => {
  const params = options.url.includes('?')
    ? Object.fromEntries(new URLSearchParams(options.url.split('?')[1]))
    : {}
  return successResponse(generatePosts(params))
})

// 推荐帖子列表
Mock.mock(/\/api\/posts\/recommended(\?.+)?$/, 'get', (options) => {
  const params = options.url.includes('?')
    ? Object.fromEntries(new URLSearchParams(options.url.split('?')[1]))
    : {}
  return successResponse(generatePosts(params))
})

// // 用户帖子列表
// Mock.mock(/\/api\/users\/\w+\/posts(\?.+)?$/, 'get', (options) => {
//   const params = options.url.includes('?')
//     ? Object.fromEntries(new URLSearchParams(options.url.split('?')[1]))
//     : {}
//   return successResponse(generatePosts(params))
// })

// 搜索帖子
Mock.mock(/\/api\/posts\/search(\?.+)?$/, 'get', (options) => {
  const params = options.url.includes('?')
    ? Object.fromEntries(new URLSearchParams(options.url.split('?')[1]))
    : {}
  return successResponse(generatePosts(params))
})

// 创建帖子
Mock.mock(/\/api\/posts$/, 'post', (options) => {
  const postData = JSON.parse(options.body)
  return successResponse({
    ...postData,
    id: Mock.Random.id(),
    createTime: Mock.Random.datetime(),
    viewCount: 0,
    likeCount: 0,
    collectCount: 0,
    commentCount: 0
  })
})

// 更新帖子
Mock.mock(/\/api\/posts\/\d+$/, 'put', (options) => {
  const postData = JSON.parse(options.body)
  return successResponse(postData)
})

// 删除帖子
Mock.mock(/\/api\/posts\/\d+$/, 'delete', () => {
  return successResponse(null)
})

// 帖子详情接口
Mock.mock(/\/api\/posts\/\d+\/detail/, 'get', (options) => {
  const postId = parseInt(options.url.match(/\/posts\/(\d+)/)[1])
  const post = Mock.mock({
    id: postId,
    title: '@ctitle(5,20)',
    content: '@cparagraph(3,7)',
    'coverImage|1': ['/001.png', '/002.png', '/003.png', '/004.png', '/005.png'],
    'images|1-5': ['/001.png', '/002.png', '/003.png', '/004.png', '/005.png'],
    'tags|1-3': ['@ctitle(2,4)'],
    'viewCount|100-9999': 1000,
    'likeCount|10-999': 100,
    'collectCount|10-999': 100,
    'commentCount|0-99': 50,
    location: '@city',
    createTime: '@datetime',
    'isLiked|1': false,
    'isCollected|1': false,
    author: {
      id: '@id',
      nickname: '@cname',
      avatar: '@image("100x100")',
      'isFollowed|1': false
    }
  })
  return successResponse(post)
})

// 点赞/取消点赞帖子
Mock.mock(/\/api\/posts\/\d+\/like/, 'post', () => {
  return successResponse(null)
})

Mock.mock(/\/api\/posts\/\d+\/unlike/, 'delete', () => {
  return successResponse(null)
})

// 收藏/取消收藏帖子
Mock.mock(/\/api\/posts\/\d+\/collect/, 'post', () => {
  return successResponse(null)
})

Mock.mock(/\/api\/posts\/\d+\/uncollect/, 'delete', () => {
  return successResponse(null)
})

// ==================== 评论相关接口 ====================
// 评论列表接口
Mock.mock(/\/api\/posts\/\d+\/comments(\?.+)?$/, 'get', () => {
  const comments = Mock.mock({
    'items|5-10': [{
      'id|+1': 1,
      content: '@cparagraph(1,3)',
      'likeCount|0-99': 0,
      'isLiked|1': false,
      createTime: '@datetime',
      userId: '@id',
      nickname: '@cname',
      avatar: '@image("50x50")',
      'replies|0-3': [{
        'id|+1': 100,
        content: '@cparagraph(1)',
        'likeCount|0-99': 0,
        'isLiked|1': false,
        createTime: '@datetime',
        userId: '@id',
        nickname: '@cname',
        avatar: '@image("50x50")',
        replyTo: '@cname'
      }]
    }],
    total: 100,
    page: 1,
    limit: 10
  })
  return successResponse(comments)
})

// 点赞/取消点赞评论
Mock.mock(/\/api\/comments\/\d+\/like/, 'post', () => {
  return successResponse(null)
})

Mock.mock(/\/api\/comments\/\d+\/unlike/, 'delete', () => {
  return successResponse(null)
})

// ==================== 通知相关接口 ====================
// 获取通知列表
Mock.mock(/\/api\/notifications(\?.+)?$/, 'get', (options) => {
  const params = options.url.includes('?')
    ? Object.fromEntries(new URLSearchParams(options.url.split('?')[1]))
    : {}
  
  const notifications = Mock.mock({
    [`items|${params.limit || 10}`]: [generateNotification]
  })

  return successResponse({
    ...notifications,
    total: 100,
    page: parseInt(params.page) || 1,
    limit: parseInt(params.limit) || 20
  })
})

// 获取未读通知数量
Mock.mock(/\/api\/notifications\/unread-count/, 'get', () => {
  return successResponse({
    count: Mock.Random.integer(0, 99)
  })
})

// 标记通知为已读
Mock.mock(/\/api\/notifications\/\d+\/read/, 'put', () => {
  return successResponse({ success: true })
})

// 标记所有通知为已读
Mock.mock(/\/api\/notifications\/mark-all-read/, 'put', () => {
  return successResponse({ success: true })
})

// 删除通知
Mock.mock(/\/api\/notifications\/\d+/, 'delete', () => {
  return successResponse({ success: true })
})

// 删除所有通知
Mock.mock(/\/api\/notifications\/delete-all/, 'delete', () => {
  return successResponse({ success: true })
})

// 获取通知设置
Mock.mock(/\/api\/notifications\/settings/, 'get', () => {
  return successResponse({
    emailNotifications: '@boolean',
    pushNotifications: '@boolean',
    notifyOnLike: '@boolean',
    notifyOnComment: '@boolean',
    notifyOnFollow: '@boolean',
    notifyOnMention: '@boolean',
    notifyOnSystem: '@boolean'
  })
})

// 更新通知设置
Mock.mock(/\/api\/notifications\/settings/, 'put', (options) => {
  const settings = JSON.parse(options.body)
  return successResponse(settings)
})

// 发送通知（系统管理员使用）
Mock.mock(/\/api\/notifications\/send/, 'post', (options) => {
  const data = JSON.parse(options.body)
  return successResponse({
    ...data,
    id: Mock.Random.id(),
    createTime: Mock.Random.datetime()
  })
})

// ==================== 文件上传相关接口 ====================
// 文件上传接口
Mock.mock(/\/api\/upload\/image/, 'post', () => {
  return successResponse({
    url: Mock.Random.image('800x600'),
    filename: '@title(5,10)',
    size: '@integer(50000,2000000)',
    type: 'image/jpeg'
  })
})

// 文件上传相关接口
Mock.mock(/\/api\/upload\/file/, 'post', (options) => {
  return successResponse({
    url: Mock.Random.image('800x600'),
    filename: Mock.Random.word(5,10) + '.jpg',
    size: Mock.Random.integer(50000, 2000000),
    type: 'image/jpeg',
    id: Mock.Random.guid()
  })
})

Mock.mock(/\/api\/upload\/multiple/, 'post', (options) => {
  const files = Mock.mock({
    'items|1-5': [{
      url: '@image("800x600")',
      filename: '@word(5,10).jpg',
      size: '@integer(50000, 2000000)',
      type: 'image/jpeg',
      id: '@guid'
    }]
  })
  return successResponse(files.items)
})

Mock.mock(/\/api\/upload\/image/, 'post', (options) => {
  return successResponse({
    url: Mock.Random.image('800x600'),
    filename: Mock.Random.word(5,10) + '.jpg',
    size: Mock.Random.integer(50000, 2000000),
    type: 'image/jpeg',
    id: Mock.Random.guid()
  })
})

Mock.mock(/\/api\/upload\/video/, 'post', (options) => {
  return successResponse({
    url: '/mock-video.mp4',
    filename: Mock.Random.word(5,10) + '.mp4',
    size: Mock.Random.integer(1000000, 10000000),
    type: 'video/mp4',
    id: Mock.Random.guid()
  })
})

Mock.mock(/\/api\/upload\/files\/\w+/, 'delete', () => {
  return successResponse({ success: true })
})

Mock.mock(/\/api\/upload\/files\/\w+/, 'get', (options) => {
  const fileId = options.url.match(/\/files\/(\w+)/)[1]
  return successResponse({
    id: fileId,
    url: Mock.Random.image('800x600'),
    filename: `file-${fileId}.jpg`,
    size: Mock.Random.integer(50000, 2000000),
    type: 'image/jpeg'
  })
})

Mock.mock(/\/api\/upload\/user-files(\?.+)?$/, 'get', (options) => {
  const params = options.url.includes('?')
    ? Object.fromEntries(new URLSearchParams(options.url.split('?')[1]))
    : {}
  
  const files = Mock.mock({
    [`items|${params.limit || 10}`]: [{
      id: '@guid',
      url: '@image("800x600")',
      filename: '@word(5,10).jpg',
      size: '@integer(50000, 2000000)',
      type: 'image/jpeg',
      createTime: '@datetime'
    }]
  })

  return successResponse({
    ...files,
    total: 100,
    page: parseInt(params.page) || 1,
    limit: parseInt(params.limit) || 20
  })
})

export default Mock